package com.willian.andrappfw.utils;

import android.app.Activity;

import java.util.ArrayList;
import java.util.Iterator;

public class ActivityStack {
    private static final ArrayList<Activity> mActivityHeap = new ArrayList();

    public ActivityStack() {
    }

    public static void add(Activity activity) {
        mActivityHeap.add(activity);
    }

    public static void remove(Activity activity) {
        mActivityHeap.remove(activity);
    }

    public static void backToFirst() {
        while(mActivityHeap.size() >= 2) {
            int index = mActivityHeap.size() - 1;
            Activity activity = (Activity)mActivityHeap.get(index);
            mActivityHeap.remove(index);
            activity.finish();
        }

    }

    public static void backTo(Class<?> target) {
        backTo(target, false);
    }

    public static void backTo(Class<?> target, boolean closeTarget) {
        for(int i = mActivityHeap.size() - 1; i > 0; --i) {
            Activity activity = (Activity)mActivityHeap.get(i);
            if (target.isInstance(activity)) {
                if (closeTarget) {
                    mActivityHeap.remove(i);
                    activity.finish();
                }
                break;
            }

            mActivityHeap.remove(i);
            activity.finish();
        }

    }

    public static void backTo(int step) {
        for(int i = 0; i < step && mActivityHeap.size() > 0; ++i) {
            int index = mActivityHeap.size() - 1;
            Activity activity = (Activity)mActivityHeap.get(index);
            mActivityHeap.remove(index);
            activity.finish();
        }

    }

    public static void closeAll() {
        Iterator var0 = mActivityHeap.iterator();

        while(var0.hasNext()) {
            Activity activity = (Activity)var0.next();
            activity.finish();
        }

        mActivityHeap.clear();
    }

    public static void closeAllExcept(Class<?> target) {
        for(int i = mActivityHeap.size() - 1; i >= 0; --i) {
            Activity activity = (Activity)mActivityHeap.get(i);
            if (!target.isInstance(activity)) {
                mActivityHeap.remove(i);
                activity.finish();
            }
        }

    }

    public static void printStackInfo() {
        LogUtils.d(ActivityStack.class.getSimpleName(), "--------------Start---------------");

        for(int i = 0; i < mActivityHeap.size(); ++i) {
            LogUtils.d(ActivityStack.class.getSimpleName(), "Activity: " + ((Activity)mActivityHeap.get(i)).getClass().getSimpleName() + ", position: " + i);
        }

        LogUtils.d(ActivityStack.class.getSimpleName(), "--------------End---------------");
    }
}
